package edu.uwosh.cs342.project4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import edu.uwosh.cs342.project4.model.Place;

public class PlaceRequest {

	// Create our transport.
	// private static final HttpTransport transport = new ApacheHttpTransport();

	// Fill in the API key you want to use.
	private static final String API_KEY = "AIzaSyAAOOJT3Jn-jQc-OaqnsA3sosK-uhyAGbM";
	// The different Places API endpoints.
	private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
	double latitude, longitude;
	
	public PlaceRequest (double lat, double lng){
		latitude = lat;
		longitude = lng;
	}

	public ArrayList<Place> performSearch() throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(PLACES_SEARCH_URL + "key=" + API_KEY
				+ "&location=" + latitude + "," + longitude + "&radius=" + 500
				+ "&sensor=" + "false");
		System.out.println(httppost.toString());
		HttpResponse response = httpclient.execute(httppost);
		InputStream inputStream = response.getEntity().getContent();

		String jString = inputStreamAsString(inputStream);
		Log.d("output", jString);
		
		ArrayList <Place> placesArray= new ArrayList<Place>();
		
		JSONObject jsonObject = new JSONObject(jString);
		JSONArray jsonResultsArray = jsonObject.getJSONArray("results");
		Log.d("size", Integer.toString(jsonResultsArray.length()));
		
		JSONObject temp;
		Place pl = null;
		for (int i = 0; i < jsonResultsArray.length(); i++) {
			pl = new Place();
			temp = jsonResultsArray.getJSONObject(i);
			pl.setName(temp.getString("name"));
			
			JSONObject jsonLocation = temp.getJSONObject("geometry").getJSONObject("location");

			String lat = jsonLocation.getString("lat");
			String lng = jsonLocation.getString("lng");
			
			pl.setLat(lat);
			pl.setLng(lng);
			placesArray.add(pl);
			Log.d("add", "place added");
		}

		return placesArray;
	}

	public static String inputStreamAsString(InputStream stream)
			throws IOException {
		BufferedReader BR = new BufferedReader(new InputStreamReader(stream));
		StringBuilder SB = new StringBuilder();
		String line1 = null;

		while ((line1 = BR.readLine()) != null) {
			SB.append(line1 + "\n");
		}

		BR.close();
		return SB.toString();
	}
}
